package com.qd.system.service.user;

import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.system.mapper.BaseUserInfoBindMapper;
import com.qd.system.model.BaseUserInfoBind;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * 用户绑定信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class BaseUserInfoBindService extends BaseService<BaseUserInfoBindMapper, BaseUserInfoBind> {

    private static final String PREFIX_ID = "sys_base_user_info_bind_uid_{0}";

    private final RedisTemplateUtil<BaseUserInfoBind> redisTemplateUtil;


    /**
     * 保存
     *
     * @param model 数据库对象
     * @return 成功 or 失败
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(BaseUserInfoBind model) {
        try {
            return super.save(model);
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 删除，单个
     *
     * @param uid 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String uid) {
        final BaseUserInfoBind model = Optional.ofNullable(getById(uid)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(uid)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param uid 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String uid) {
        boolean exists = false;
        if (StringUtils.hasLength(uid)) {
            final BaseUserInfoBind model = getById(uid);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param uid 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public BaseUserInfoBind getById(String uid) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, uid);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(uid), BaseUserInfoBind.class);
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(BaseUserInfoBind model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getUid()));
    }
}